package logic

import (
	"context"
	"fmt"
	"house1/model/cache"
	"house1/model/mysql"
	"house1/pkg"

	"house1/houserpc/houserpc"
	"house1/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User

	mysql.DB.Debug().Where("phone=?", in.Phone).Find(&finduser)

	if finduser.ID == 0 {
		return nil, fmt.Errorf("用户不存在,请前去注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "Sendsms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("短信验证码验证失败,请重新输入")
	}

	if finduser.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码失误")
	}

	return &houserpc.LoginResponse{}, nil
}
